<?php
ini_set('date.timezone','Asia/Shanghai');
//error_reporting(E_ERROR);
//$input = file_get_contents("php://input");

require_once '../../application/libraries/aliyun-dysms-php-sdk/api_demo/SmsDemo.php'; //这个是实例化的类
require_once '../../application/libraries/JssdkLogic.php';
require_once "../lib/WxPay.Api.php";
require_once '../lib/WxPay.Notify.php';
require_once 'log.php';
	
//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);

class PayNotifyCallBack extends WxPayNotify
{
	
	//查询订单 ReplyNotify
	public function Queryorder($transaction_id)
	{ 	
		/* $device_recharge = '{"id":"id_123456","ts":123456,"result":0}';
		$device_recharge2 = json_decode($device_recharge,true);
		print_r($device_recharge2);
		
		die; */
		
		$input = new WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);
		$result = WxPayApi::orderQuery($input); 
		
		if($result["return_code"] == "SUCCESS"){ 
			$hostname = WxPayConfig::HOST;
			$username = WxPayConfig::USERNAME;
			$password = WxPayConfig::PASSWORDE;
			$database = WxPayConfig::DATABASSE;
				
		
			$id = WxPayConfig::ID;
			$signkey = WxPayConfig::SIGNKEY;
			
			$con = mysql_connect($hostname,$username,$password);
			if (!$con)
			{
				die('Could not connect: ' . mysql_error());
			}
			mysql_select_db($database, $con);
			$out_trade_no = substr($result['out_trade_no'],0,13);				
			//$out_trade_no = '1517286189749';
			$device_sql = "SELECT * FROM mifi_order WHERE order_on = ".$out_trade_no."";
			$device_result = mysql_query($device_sql);
			$order = mysql_fetch_array($device_result);
			
			$device_id = $order['device_id'];
			$package_id = $order['goods_on'];
			
		/* 	echo '<br/>';
			echo $out_trade_no;echo '<br/>';
			echo $device_id;echo '<br/>';
			echo $package_id;
			die;
			//print_r($out_trade_no);
			//print_r($device_id);
			//print_r($package_id); */
			
			//充值
			if($order['paystate'] == 0){
				
				$endtime = date("YmdHis"); //下单时间	
				
				
				//拿到设备
				$device_sql = "SELECT * FROM mifi_device WHERE device_sn = ".$device_id."";
				$device_result = mysql_query($device_sql);
				$device = mysql_fetch_array($device_result);
				
				//拿到用户
				$user_id = $order['user_id'];
				$user_sql = "SELECT * FROM mifi_users WHERE user_id = ".$user_id."";
				$user_result = mysql_query($user_sql);
				$user = mysql_fetch_array($user_result);
				
				//拿到套餐
				$package_id = $order['goods_on'];
				$package_sql = "SELECT * FROM mifi_recharge WHERE package_id = ".$package_id."";
				$package_result = mysql_query($package_sql);
				$package = mysql_fetch_array($package_result);
				
				//调用充值接口！！！！！！！！！！！！！！！！！！！！！！！！（修改前注释）
				$device_recharges = WxPayApi::device_recharge($device_id,$out_trade_no,$package_id);
				$recharge = json_decode($device_recharges,true);
				//调用充值接口！！！！！！！！！！！！！！！！！！！！！！！！（修改前注释）
				
				if($recharge['result'] == 0){
						//修改设备状态 
					$sql = "UPDATE `mifi_order` SET `package_paystate`='1' WHERE (`order_on`=".$out_trade_no.")";
					$results = mysql_query($sql);
				}
				
				//代理分佣
				// if(!empty($device['agent2'])){

				// 	$agent_user_id = $device['agent2'];
				// 	//分佣比例
				// 	$agent_sql = "SELECT * FROM mifi_config WHERE name = 'agent2'";
				// 	$agent_result = mysql_query($agent_sql);
				// 	$agent = mysql_fetch_array($agent_result);
					
				// 	$commission_data['agent_user_id'] = $agent_user_id;
				// 	$commission_data['order_id'] = $out_trade_no;
				// 	$commission_data['addtime'] = date("YmdHis");
				// 	$commission_data['device_sn'] = $device_id;
				// 	$commission_data['settlement'] = 0;
				// 	$commission_data['money'] = ($order['order_money']*$agent['value']);
				// 	$commission_data['flow'] = $package['flow'];
				// 	$commission_data['addtime2'] = time();	

				// 	$commission_into = "INSERT INTO `mifi_commission` (`agent_user_id`, `order_id`, `addtime`, `device_sn`, `settlement`, `money`, `flow`, `addtime2`) VALUES ('".$commission_data['agent_user_id']."', '".$commission_data['order_id']."','".$commission_data['addtime']."','".$commission_data['device_sn']."','".$commission_data['settlement']."', '".$commission_data['money']."','".$commission_data['flow']."', '".$commission_data['addtime2']."')";
				// 	$result_commission_into = mysql_query($commission_into);
				// }
	
				// if(!empty($device['agent1'])){
				// 	$agent_user_id = $device['agent1'];
				// 	//分佣比例
				// 	$agent_sql = "SELECT * FROM mifi_config WHERE name = 'agent1'";
				// 	$agent_result = mysql_query($agent_sql);
				// 	$agent = mysql_fetch_array($agent_result);

				// 	$commission_data_agent1['agent_user_id'] = $agent_user_id;
				// 	$commission_data_agent1['order_id'] = $out_trade_no;
				// 	$commission_data_agent1['addtime'] = date("YmdHis");
				// 	$commission_data_agent1['device_sn'] = $device_id;
				// 	$commission_data_agent1['settlement'] = 0;
				// 	$commission_data_agent1['money'] = ($order['order_money']*$agent['value']);
				// 	$commission_data_agent1['flow'] = $package['flow'];
				// 	$commission_data_agent1['addtime2'] = time();	

				// 	$commission_into = "INSERT INTO `mifi_commission` (`agent_user_id`, `order_id`, `addtime`, `device_sn`, `settlement`, `money`, `flow`, `addtime2`) VALUES ('".$commission_data_agent1['agent_user_id']."', '".$commission_data_agent1['order_id']."','".$commission_data_agent1['addtime']."','".$commission_data_agent1['device_sn']."','".$commission_data_agent1['settlement']."', '".$commission_data_agent1['money']."','".$commission_data_agent1['flow']."', '".$commission_data_agent1['addtime2']."')";
				// 	$result_commission_into = mysql_query($commission_into);
				// }else{
				// 	//$agent_user_id = $device['agent1'];
				// 	//分佣比例
				// 	$agent_sql = "SELECT * FROM mifi_config WHERE name = 'agent1'";
				// 	$agent_result = mysql_query($agent_sql);
				// 	$agent = mysql_fetch_array($agent_result);

				// 	$commission_data_agent1['agent_user_id'] = '10000';
				// 	$commission_data_agent1['order_id'] = $out_trade_no;
				// 	$commission_data_agent1['addtime'] = date("YmdHis");
				// 	$commission_data_agent1['device_sn'] = $device_id;
				// 	$commission_data_agent1['settlement'] = 0;
				// 	$commission_data_agent1['money'] = ($order['order_money']*$agent['value']);
				// 	$commission_data_agent1['flow'] = $package['flow'];
				// 	$commission_data_agent1['addtime2'] = time();	

				// 	$commission_into = "INSERT INTO `mifi_commission` (`agent_user_id`, `order_id`, `addtime`, `device_sn`, `settlement`, `money`, `flow`, `addtime2`) VALUES ('".$commission_data_agent1['agent_user_id']."', '".$commission_data_agent1['order_id']."','".$commission_data_agent1['addtime']."','".$commission_data_agent1['device_sn']."','".$commission_data_agent1['settlement']."', '".$commission_data_agent1['money']."','".$commission_data_agent1['flow']."', '".$commission_data_agent1['addtime2']."')";
				// 	$result_commission_into = mysql_query($commission_into);
				// }
				
				
				//修改设备状态
				$sql = "UPDATE `mifi_order` SET `paystate`='1',`endtime`='".$endtime."' WHERE (`order_on`=".$out_trade_no.")";
				$results = mysql_query($sql);
				$jihuo_sql = "UPDATE `mifi_device` SET `jihuo`='1' WHERE (`device_sn`='".$device_id."')";
				$jihuo_result = mysql_query($jihuo_sql);
				
				//$device_chaxuns = WxPayApi::device_chaxun($device_id);
				//$device_data = "".$device_chaxuns['last_expire_date']."";
				
				if($package['time'] == 6){
					$flow = "6个月流量套餐";
				}
				if($package['time'] == 12){
					$flow = "12个月流量套餐";
				}
				if($package['time'] == 24){
					$flow = "24个月流量套餐";
				}
				// if($order['goods_on'] == 4){
				// 	$flow = "12个月流量套餐";
				// }
				
				//短信
				//$SmsDemo = new SmsDemo();
				//$response = $SmsDemo->sendSms($user['mobile'],$device_id,$user['nickname'],$flow,$device_data);
				//$response = $SmsDemo->sendSms('18617165778','154544','najn','taocan','123213');
				
				//微信推送
				$appid = WxPayConfig::APPID;
				$secret = WxPayConfig::APPSECRET;
				
				//拿到用户微信
				$user_sql_wx = "SELECT * FROM mifi_users_weixin WHERE user_id = ".$user_id."";
				$user_result_wx = mysql_query($user_sql_wx);
				$user_wx = mysql_fetch_array($user_result_wx);
					
				$JssdkLogic = new JssdkLogic($appid,$secret);
				$data = $JssdkLogic->push_msg($user_wx['openid'],'您的设备'.$device_id.'充值'.$flow.',充值成功！');
				
			}
		}
		
		Log::DEBUG("query1:" . json_encode($result));
		if(array_key_exists("return_code", $result)
			&& array_key_exists("result_code", $result)
			&& $result["return_code"] == "SUCCESS"
			&& $result["result_code"] == "SUCCESS")
		{
			return true;
		}
		$result = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
		return $result;
		
		//exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
		
		//return false;
	}
	
	//重写回调处理函数
	public function NotifyProcess($data, &$msg)
	{	
		Log::DEBUG("call back:" . json_encode($data));
		$notfiyOutput = array();
		
		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			return false;
		}
		//查询订单，判断订单真实性
		if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			return false;
		}
		
		
		return true;
	}
	
}

//$input = new PayNotifyCallBack();
//$input->Queryorder('123');


Log::DEBUG("begin notify");
$notify = new PayNotifyCallBack();
$notify->Handle(false);
